module Ruiqu
  class BusinessCompaniesController < BaseController
    before_action :get_company, only:[:show, :edit, :update, :destroy]
    def index
      get_search_params
      @q = current_store.business_companies.ransack(params[:q])
      @companies = @q.result

      respond_to do |format|
        format.html
        format.csv { render text: @companies.to_csv }
        format.xls
      end
    end

    def new
      @company = current_store.business_companies.new
    end

    def create
      company = current_store.business_companies.new(company_params)
      if company.save
        redirect_to ruiqu_business_companies_path
      else
        render :new
      end
    end

    def show
    end

    def edit
    end

    def update
      @company.update!(company_params)
      redirect_to ruiqu_business_companies_path
    end

    def lead_in

    end

    def csv_create
      csv_text = params[:data_file].tempfile
      csv = CSV.parse(csv_text, :headers => true)
      csv.each do |item|
        company = BusinessCompany.new
        company.company_name = item[0]
        company.user_name = item[1]
        company.phone_number = item[2]
        company.address = item[3]
        company.remark = item[4]
        company.store_id = current_store.id
        company.save!
      end
      redirect_to ruiqu_business_companies_path
    end

    def destroy
      @company.destroy
      redirect_to ruiqu_business_companies_path
    end

    private
    def company_params
      params.require(:business_company).permit(
        :user_name,
        :phone_number,
        :address,
        :company_name,
        :remark
      )
    end

    def get_company
      @company = current_store.business_companies.find(params[:id])
    end

    def get_search_params
      params[:q] ||= {}
      @search_params = params[:q][:phone_number_or_company_name_or_user_name_or_address_cont]
    end
  end
end
